package org.example.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

public class MyBatisUtil {

    private MyBatisUtil(){}

    //定义SqlSessionFactory
    private static SqlSessionFactory  factory = null;

    static {
        //使用静态块 创建一次SqlSessionFactory
        try {
            String config = "mybatis.xml";
            //读取配置文件
            InputStream in = Resources.getResourceAsStream(config);
            //创建sqlSessionFactory对象
            factory = new SqlSessionFactoryBuilder().build(in);

        }catch (Exception e) {
            factory = null;
            e.printStackTrace();
        }

    }

    private static ThreadLocal<SqlSession> t = new ThreadLocal<SqlSession>();



    //获取SqlSession对象
    public static SqlSession getSqlSession() {
        SqlSession sqlSession = null;
        sqlSession = t.get();

        if (sqlSession == null) {

            if (factory != null) {
                sqlSession = factory.openSession(true);

                t.set(sqlSession);
            }

        }

        return sqlSession;
    }


    public static void close(SqlSession sqlSession) {
        if (sqlSession != null) {
            sqlSession.close();
            t.remove();
        }
    }
}
